import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import type { PaginationProps } from "@pureadmin/table";
import { type Ref, reactive, ref, onMounted, toRaw, watch } from "vue";
import { useRouterNavigation } from "@/router/utils";
import { dealDataExcept, dealDataRide, dealDataAdd } from "@/utils/common";
import { useUserStoreHook } from "@/store/modules/user";
import { goodsNameRend, goodsCodeRend } from "@/utils/tableColumns";

import { getShopCarList, delShopCart, upShopCart } from "@/api/home/shopCar";
import { addStoreOrder } from "@/api/order/store";
import { getDepositoryPage } from "@/api/common";
import { DictTag } from "@/components/common/DictTag";

export function useShopCar(tableRef?: Ref) {
  const treeRef = ref();
  const form = reactive({
    searchContent: "",
    pageNum: 1,
    pageSize: 10
  });
  const submitForm = reactive({
    depositoryId: "",
    des: "",
    sumAmount: 0,
    totalPrice: 0
  });
  const warehouseList = ref([]); // 仓库列表
  const tableSelectList = ref([]);
  const curRow = ref();
  const dataList = ref([]);
  const treeIds = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const treeSearchValue = ref();
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "商品名称/规格名称",
      prop: "goodsName",
      align: "left",
      minWidth: 150,
      cellRenderer: goodsNameRend
    },
    {
      label: "商品编码/规格编码",
      prop: "goodsCode",
      align: "left",
      minWidth: 150,
      cellRenderer: goodsCodeRend
    },
    {
      label: "商品条码",
      align: "left",
      minWidth: 120,
      prop: "barCode",
      formatter: ({ barCode }) => barCode || "--"
    },
    {
      label: "商品类型",
      prop: "goodsType",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <DictTag dict-type="PRODUCT_TYPE" dict-value={row.goodsType} />
      )
    },
    {
      label: "进价(元)",
      prop: "buyPrice",
      minWidth: 120,
      formatter: ({ buyPrice }) => dealDataExcept(buyPrice)
    },
    {
      label: "商品数量",
      prop: "amount",
      minWidth: 160,
      cellRenderer: ({ row }) => (
        <el-input-number
          v-model={row.amount}
          onChange={() => handleUp(row, 1)}
          class="!w-[145px]"
          placeholder="请输入"
          precision={0}
          min={1}
          max={99999}
        />
      )
    },
    {
      label: "发货仓", // goodsType 2:兑礼商品 不能调整发货仓
      prop: "gmtCreate",
      minWidth: 150,
      cellRenderer: ({ row }) => (
        <div>
          {row.goodsType == 2 ? (
            <div>{row.depositoryType == 1 ? "佳叽仓库" : "供应商仓"}</div>
          ) : (
            <el-select
              v-model={row.depositoryType}
              onChange={() => handleUp(row, 2)}
              class="!w-[115px]"
              placeholder="请选择"
            >
              <el-option label="佳叽仓库" value={1} />
              <el-option label="供应商仓" value={2} />
            </el-select>
          )}
        </div>
      )
    },
    {
      label: "小计",
      prop: "totalPrice",
      minWidth: 125,
      cellRenderer: ({ row }) => (
        <div class="text-red-500 font-bold">
          ¥{dealDataExcept(row.totalPrice)}
        </div>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 100,
      align: "center",
      slot: "operations"
    }
  ];

  // 查看商品详情
  const { push } = useRouterNavigation();
  const showGoodsDetail = row => {
    push({
      path: "/home/goods/detail",
      query: { id: row.id }
    });
  };

  // 删除
  const handleDelete = async row => {
    await delShopCart(row.id);
    tableRef.value.getTableRef().clearSelection();
    message("删除成功", { type: "success" });
    onSearch();
  };

  // 修改
  const handleUp = async (row, type) => {
    if (!row.amount) {
      row.amount = 1;
    }
    let newParams = { ...row };
    let totalPrice = dealDataRide(newParams.amount, newParams.buyPrice);
    newParams.totalPrice = totalPrice;
    await upShopCart(newParams);
    if (type == 1) {
      row.totalPrice = totalPrice;
      calcGoodsAmount();
    } else {
      tableRef.value.getTableRef().clearSelection();
      await onSearch();
    }
    message("修改成功", { type: "success" });
  };

  // 提交订单
  const submitOrder = () => {
    if (!submitForm.depositoryId)
      return message("请选择到货仓库", { type: "warning" });
    ElMessageBox.confirm("确认提交订单?", "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    }).then(async () => {
      let warehouse = warehouseList.value.find(
        v => v.id == submitForm.depositoryId
      );
      let params = {
        depositoryId: submitForm.depositoryId, // 到货仓库id
        depositoryName: warehouse.depositoryName, // 到货仓库
        des: submitForm.des, // 备注
        goodsIds: tableSelectList.value.map(v => v.goodsId), // 购物车内商品ids
        orderMethod: 2, // 下单方式 1 直接下单 2 购物车下单
        storeId: useUserStoreHook().loginStoreId // 门店id
      };
      await addStoreOrder(params);
      submitForm.des = "";
      submitForm.sumAmount = 0;
      submitForm.totalPrice = 0;
      tableRef.value.getTableRef().clearSelection();
      message("提交订单成功", { type: "success" });
      onSearch();
    });
  };

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    form.pageNum = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    tableSelectList.value = val;
    calcGoodsAmount();
  }

  const calcGoodsAmount = () => {
    let amount = 0;
    let totalPrice = 0;
    for (const item of tableSelectList.value) {
      amount = dealDataAdd(item.amount, amount);
      totalPrice = dealDataAdd(item.totalPrice, totalPrice);
    }
    submitForm.sumAmount = amount;
    submitForm.totalPrice = dealDataExcept(totalPrice) || 0;
  };

  async function onSearch() {
    loading.value = true;
    const { data } = await getShopCarList(toRaw(form));
    dataList.value = data.records || [];
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;
    sessionStorage.removeItem("isHaveAddGoods");
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  /** 菜单权限-保存 */
  function handleSave() {
    const { id, name } = curRow.value;
    // 根据用户 id 调用实际项目中菜单权限修改接口
    console.log(id, treeRef.value.getCheckedKeys());
    message(`角色名称为${name}的菜单权限修改成功`, {
      type: "success"
    });
  }

  onMounted(async () => {
    onSearch();

    // 获取仓库列表
    let params = {
      type: 0,
      status: 0,
      pageNum: 1,
      pageSize: 500
    };
    getDepositoryPage(params).then(res => {
      warehouseList.value = res.data?.records || [];
      if (warehouseList.value.length > 0) {
        submitForm.depositoryId = warehouseList.value[0].id;
      }
    });
  });

  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  return {
    form,
    submitForm,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,
    dataList,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    warehouseList,
    tableSelectList,
    onSearch,
    resetForm,
    handleSave,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    showGoodsDetail,
    submitOrder
  };
}
